

import 'dart:convert';
import 'package:aqua_plunge/model/payment.dart';
import 'package:aqua_plunge/model/purchase.dart';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import '../http/Url.dart';
import '../util/header_util.dart';

class PurchaseDao{

  static Utf8Decoder utf8decoder = const Utf8Decoder();

  ///充值商品列表
  static Future<List<Purchase>?> getGoodslist() async {
    List<Purchase> list = [];
    var httpurl = Uri.parse(AppUrl.getGoodsSearch);
    final bodyParams = {'isIncludeSubscription': false, 'payChannel': 'IAP'};
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: json.encode(bodyParams),
          encoding: const Utf8Codec());
      if (response.statusCode == 200) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if(result['data'] != null){
           var maps = result['data'] as List<dynamic>;
           list = maps.map((json) => Purchase.fromJson(json)).toList();
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
    return list;
  }


  ///创建订单接口
  static Future<Payment> createRecharge(int goodsCode) async {
    
    late Payment payment;
    
    var httpurl = Uri.parse(AppUrl.createRecharge);
    final bodyParams = {
      'entry': '',
      'goodsCode': goodsCode,
      'payChannel':'IAP',
      'source':''
    };
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: json.encode(bodyParams),
          encoding: const Utf8Codec());
      if (response.statusCode == 200) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if(result['data'] != null){
          payment = Payment.fromJson(result['data']);
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
    return payment;
  }


  ///验单接口    订单号/购买凭证/内购交易号，苹果返回的交易流水号
  static Future paymentCheck(String orderno,String payload,String transactionid,Function? success) async {
    var httpurl = Uri.parse(AppUrl.paymentCheck);
    final bodyParams = {
      'orderNo': orderno,
      'payload': payload,
      'transactionId':transactionid,
      'type':'1'
    };
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: json.encode(bodyParams),
          encoding: const Utf8Codec());
      if (response.statusCode == 200) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if(result['data'] != null && success != null){
          success();
          debugPrint('=========createrecharge=${result['data']}');
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
  }




  ///消耗金币
  static Future<void> reviewModelConsume(int outlay,Function success,Function fail) async {

    var httpurl = Uri.parse(AppUrl.reviewModeConsume);
    final bodyParams = {'outlay': outlay, 'source': 'iap'};
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: json.encode(bodyParams),
          encoding: const Utf8Codec());
      if (response.statusCode == 200) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if(result['success'] == false){
          fail(result['msg']);
        }
        if(result['data'] != null){
          success();
          debugPrint('review result--------->${result['data']}');
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
  }


}